﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Kokomo.Environment.Services
{
	public static class ImageHelper
	{
		public static string GetImageKey(DependencyObject obj)
		{
			return (string)obj.GetValue(ImageKeyProperty);
		}

		public static void SetImageKey(DependencyObject obj, string value)
		{
			obj.SetValue(ImageKeyProperty, value);
		}

		// Using a DependencyProperty as the backing store for ImageKey.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty ImageKeyProperty =
			DependencyProperty.RegisterAttached("ImageKey", typeof(string), typeof(ImageHelper), new UIPropertyMetadata(OnImageKeyChanged));

		private static void OnImageKeyChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
		{
			Image image = target as Image;
			if (image != null)
				UpdateImageSource(image);
		}

		public static IImageProvider GetImageProvider(DependencyObject obj)
		{
			return (IImageProvider)obj.GetValue(ImageProviderProperty);
		}

		public static void SetImageProvider(DependencyObject obj, IImageProvider value)
		{
			obj.SetValue(ImageProviderProperty, value);
		}

		// Using a DependencyProperty as the backing store for ImageProvider.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty ImageProviderProperty =
			DependencyProperty.RegisterAttached("ImageProvider", typeof(IImageProvider), typeof(ImageHelper), new UIPropertyMetadata(OnImageProviderChanged));

		private static void OnImageProviderChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
		{
			Image image = target as Image;
			if (image != null)
				UpdateImageSource(image);
		}

		private static void UpdateImageSource(Image image)
		{
			if (image == null) throw new ArgumentNullException("image");

			image.Source = DetermineImageSource(
				GetImageKey(image),
				GetImageProvider(image)
				);
		}

		public static ImageSource DetermineImageSource(
			string imageKey,
			IImageProvider imageProvider
			)
		{
			if (imageKey == null) return null;

			if (imageProvider == null)
				imageProvider = EnvironmentServices.GetService<IImageProvider>();
			if (imageProvider == null) return null;

			ImageSource imageSource = imageProvider.GetImage(imageKey);
			return imageSource;
		}
	}
}
